<template>
  <div>
    <PageTitle>
      <template #prepend>
        <svg-icon
          icon-class="Monitor"
          style="font-size: 24px; margin-right: 8px"
        />
      </template>
      Terminal
      <template #buttons>
        <el-button
          text
          @click="$router.push({ path: `/tms/terminal/blacklist` })"
        >
          <svg-icon icon-class="Setting" class-name="mr-1" />
          {{ $t('menu.M_1040000200') }}
        </el-button>
      </template>
    </PageTitle>

    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="totalPage"
      :current-page="pageIndex"
      @current-change="currentChangeHandle"
    >
      <el-form class="p-4" inline @submit.prevent.native>
        <el-form-item>
          <el-input
            v-model="listQuery.devSn"
            :placeholder="$t('device.sn')"
            clearable
            maxlength="32"
            @keyup.enter.native="search()"
            @clear="search"
            @blur="() => (listQuery.devSn = listQuery.devSn.trim())"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="listQuery.operatorName"
            :placeholder="$t('operator.name')"
            clearable
            maxlength="256"
            @keyup.enter.native="search()"
            @clear="search"
            @blur="
              () => (listQuery.operatorName = listQuery.operatorName.trim())
            "
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="listQuery.modelCode"
            :placeholder="$t('device.modelCode')"
            clearable
            filterable
            @change="selectModelHandle"
          >
            <el-option
              v-for="item in deviceModels"
              :key="item.modelId"
              :label="item.modelCode"
              :value="item.modelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="listQuery.devStatus"
            :placeholder="$t('device.activeStatus')"
            clearable
            filterable
            @change="selectStatusHandle"
          >
            <el-option :value="9" :label="$t('device.inProductionStatus')" />
            <el-option :value="1" :label="$t('device.activateStatus')" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-select-->
        <!--            v-model="listQuery.isImportByOperator"-->
        <!--            :placeholder="$t('device.isBindOperator')"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            @change="selectBindHandle"-->
        <!--          >-->
        <!--            <el-option :value="1" :label="$t('device.alreadyBindOperator')"/>-->
        <!--            <el-option :value="0" :label="$t('device.notBindOperator')"/>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button class="w-8" type="primary" @click="search()">
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button class="w-8" type="primary" @click="reset">
            <svg-icon icon-class="refresh" />
          </el-button>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" :loading="exportLoading" class="p-1.5" @click="exportDevice">-->
        <!--            <svg-icon icon-class="download" class="text-lg" />-->
        <!--          </el-button>-->
        <!--        </el-form-item>-->
      </el-form>
      <el-table v-loading="dataListLoading" :data="dataList" stripe>
        <el-table-column prop="devSn" :label="$t('device.sn')" align="left">
          <template v-slot="scope">
            <div
              class="cursor-pointer"
              @click="terminalView(scope.row.devId, scope.row.bindOperatorId)"
            >
              {{ scope.row.devSn }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="modelCode" :label="$t('device.modelCode')" />
        <el-table-column
          prop="manufacturerName"
          :label="$t('device.manufacturer')"
        />
        <el-table-column
          prop="operatorName"
          :label="$t('device.operatorName')"
        />
        <el-table-column
          prop="isOnline"
          :label="$t('device.status')"
          width="100px"
        >
          <template v-slot="scope">
            <el-tag
              v-if="scope.row.isOnline == 1"
              size="small"
              type="success"
              :class="`flow-state-tag-${scope.row.isOnline}`"
              >{{ $t('device.online') }}</el-tag
            >
            <el-tag
              v-if="scope.row.isOnline == 0"
              size="small"
              type="info"
              :class="`flow-state-tag-${scope.row.isOnline}`"
              >{{ $t('device.offline') }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="isOnline" :label="$t('device.activeStatus')">
          <template v-slot="scope">
            {{
              scope.row.devStatus == 1
                ? $t('device.activateStatus')
                : $t('device.inProductionStatus')
            }}
          </template>
        </el-table-column>
        <el-table-column prop="activeTime" :label="$t('device.activeTime')">
          <template v-slot="scope">
            <div :title="timeFilter(scope.row.activateTime)">
              {{ dateFilter(scope.row.activateTime) }}
              {{ scope.row.activateTime ? '' : '-' }}
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          prop="creTime"-->
        <!--          :label="$t('device.importTime')"-->
        <!--          -->
        <!--          -->
        <!--          width="180px"-->
        <!--        >-->
        <!--          <template v-slot="scope">-->
        <!--            <div :title="scope.row.creTime | timeFilter">-->
        <!--              {{ dateFilter( scope.row.creTime ) }}-->
        <!--              {{ scope.row.creTime ? '' : '-' }}-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column width="75px">
          <template v-slot="scope">
            <div title="Terminal Full View" v-show="scope.row.bindOperatorId">
              <el-button
                text
                class="w-8"
                @click="terminalView(scope.row.devId, scope.row.bindOperatorId)"
                ><svg-icon icon-class="View"
              /></el-button>
            </div>
            <!-- <el-dropdown
              class="align-middle"
              trigger="click"
              v-show="scope.row.bindOperatorId"
            >
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    @click="
                      terminalView(scope.row.devId, scope.row.bindOperatorId)
                    "
                  >
                    <svg-icon icon-class="View" />
                    Terminal Full View
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import { timeFilter, dateFilter } from '@/filters/index'
import { pageMixins } from '@/mixins/pagination-mixins'
import { formatDate } from '@/utils/formatDate'
import { getDeviceModel, getDeviceList } from '@/api/device'
import { getToken } from '@/utils/auth'
import PageTitle from '@/components/PageTitle/index.vue'
import axios from 'axios'
import store from '@/store'
export default {
  name: 'Terminal',
  components: {
    PageTitle
  },
  mixins: [pageMixins],
  data() {
    return {
      exportLoading: false,
      modelCodeCondition: '',
      addOrUpdateDeviceVisible: false,
      listQuery: {
        manufacturerCode: '',
        modelCode: '',
        devSn: '',
        operatorName: '',
        devStatus: '',
        isImportByOperator: ''
      },
      modelCodeQuery: {
        modelCode: ''
      },
      firmOptions: [],
      deviceModels: [],
      paginationShow: true,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataList: [],
      manufacturerList: [],
      modelId: null
    }
  },
  computed: {
    colHeight() {
      return this.$store.state.common.documentClientHeight - 82 - 80
    }
  },
  mounted() {
    this.$store.commit('app/ADD_KEEP_ALIVE_LIST', 'Terminal')
    this.getDeviceModels()
    this.getDeviceList()
  },
  beforeRouteLeave(to, from, next) {
    console.log(to)
    if (to.name !== 'blacklist' && to.name !== 'deviceView') {
      this.$store.commit('app/REMOVE_KEEP_ALIVE_LIST', 'Terminal')
    }
    next()
  },
  methods: {
    timeFilter,
    dateFilter,
    iconView(src) {
      if (src) {
        return import.meta.env.VITE_APP_BASE_API + src
      }
      return require('@/assets/img/Android.png')
    },
    getDeviceModels() {
      this.deviceModels = []
      const param = {
        manufacturerCode: this.listQuery.manufacturerCode
      }
      getDeviceModel(param)
        .then((data) => {
          data.forEach((item) => {
            if (item.deviceModelSelectVos !== null) {
              item.deviceModelSelectVos.forEach((item2) => {
                this.deviceModels.push(item2)
              })
            }
          })
        })
        .catch((e) => {
          this.$confirmError(e)
          console.log(`err:${JSON.stringify(e)}`)
        })
    },
    getDeviceList() {
      this.dataListLoading = true
      getDeviceList(
        Object.assign(
          { pageNo: this.pageIndex, pageSize: this.pageSize },
          this.listQuery
        )
      )
        .then((data) => {
          console.log(data)
          this.dataList = data.data
          this.totalPage = data.rows
          this.dataListLoading = false
        })
        .catch((e) => {
          console.log(`err:${JSON.stringify(e)}`)
          this.$confirmError(e)
          this.dataListLoading = false
        })
    },
    exportDevice() {
      this.listQuery.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
      this.download(
        import.meta.env.VITE_APP_BASE_API +
          '/online/management/admin/device/export',
        this.listQuery
      )
    },
    download(url, params) {
      this.exportLoading = true
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
          'WEB-TOKEN': getToken(),
          LANG:
            localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
        },
        params: params
      })
        .then((res) => {
          const data = res.data
          if (data) {
            const dis = res.headers['content-disposition']
            const fileName = dis.split('attachment;filename=')[1]
            const url = window.URL.createObjectURL(data)
            const a = document.createElement('a')
            a.href = url
            a.download = fileName
            a.click()
          } else {
            this.$message.error(this.$t('common.export_error'))
          }
          this.exportLoading = false
        })
        .catch((e) => {
          this.exportLoading = false
          this.$confirmError(e)
        })
    },
    reset() {
      this.listQuery.modelCode = ''
      this.listQuery.devSn = ''
      this.listQuery.operatorName = ''
      this.listQuery.devStatus = null
      this.modelId = null
      this.pageIndex = 1
      this.getDeviceList()
    },
    handleSelect(model) {
      this.modelId = model.modelId
      this.listQuery.modelCode = model.modelCode
      this.search()
    },
    selectModelHandle() {
      this.getDeviceList()
    },
    selectStatusHandle() {
      this.getDeviceList()
    },
    selectBindHandle() {
      this.getDeviceList()
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.getDeviceList()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDeviceList()
    },
    search() {
      this.pageIndex = 1
      this.getDeviceList()
    },
    goToDetail(data) {
      this.$router.push({
        name: 'terminalDetail',
        query: {
          manufacturerCode: data.manufacturerCode,
          modelCode: data.modelCode,
          devSn: data.devSn
        }
      })
    },
    formatDate(timeStamp) {
      if (timeStamp !== undefined) {
        return formatDate(timeStamp, 'YYYY-MM-DD HH:mm:ss')
      }
    },
    terminalView(devId, bindOperatorId) {
      this.$router.push({
        path: `/tms/terminal/view`,
        query: {
          devId: devId,
          bindOperatorId: bindOperatorId
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.model-list {
  width: 300px;
  flex: 0 0 300px;
  height: calc(100vh - 240px);
}
.group-list {
  li {
    color: #555555;
    border-top: 1px solid #f5f7fa;
    cursor: pointer;
    padding: 16px;
    &:first-child {
      border-top: none;
    }
    &.active {
      background: #f5f7fa;
      color: #12263f;
      font-size: 1.1em;
      font-weight: 700;
    }
    .app-icon {
      width: 48px;
    }
  }
}
</style>
